<?php
// +----------------------------------------------------------------------
// | Description: about us
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
// | Date: 2018-03-06 13:37:11
// +----------------------------------------------------------------------

namespace App\Model;

use App\Common\Model;
use App\Utility\Extend\Tree;
use App\Utility\VerifyCode\HonrayVerify;
use EasySwoole\Config;
use think\Cache;
use think\Db;
use \Firebase\JWT\JWT;

class Administrator extends Model
{
    protected $fuzzyConditions = null;
    protected $clearConditions = ['ReferUserId'];
    protected $returnFields = '';
    protected $rangeConditions = null;
    protected $union_fuzzyConditions = null;
    protected $foreignConditions = null;
    protected $name = 'admin_user';

    /**
     * 获取用户所属所有用户组
     * @param  array   $param  [description]
     */
    public function groups()
    {
        return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id');
    }

    /**
     * 创建用户
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array                    $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param, $field = true)
    {
        // 验证
        $validateName = 'App\\Validate\\' . $this->convertUnderline($this->name);
        $validate = new $validateName();
        if (!$validate->scene('Create')->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $param = $this->formartData($param);
        try {
            $this->data($param)->allowField($field)->save();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 数据整理
     */
    public function formartData($param)
    {
        $this->checkCode();
        $param['PasswordSalt'] = uniqid();
        $param['Password'] = $this->user_md5($param['Password'], $param['PasswordSalt']);
        return $param;
    }

    /**
     * 用户密码加密方法
     * @param  string $str      加密的字符串
     * @param  [type] $auth_key 加密符
     * @return string           加密后长度为32的字符串
     */
    public function user_md5($str, $salt = '')
    {
        return '' === $str ? '' : md5(sha1($str) . $salt);
    }

    /**
     * [login 登录]
     * @AuthorHTL
     * @DateTime  2017-02-10T22:37:49+0800
     * @param     [string]                   $u_username [账号]
     * @param     [string]                   $u_pwd      [密码]
     * @param     [string]                   $verifyCode [验证码]
     * @param     Boolean                       $isRemember [是否记住密码]
     * @param     Boolean                    $type       [是否重复登录]
     * @return    [type]                               [description]
     */
    public function login($username, $password, $verifyCode = '', $isRemember = false, $type = false)
    {
        $instance = Config::getInstance();
        if (Cache::get('IDENTIFYING_CODE') && !$type) {
            if (!$verifyCode) {
                $this->error = '验证码不能为空';
                return false;
            }
            $captcha = new HonrayVerify($instance->getConf('captcha'));
            if (!$captcha->check($verifyCode)) {
                $this->error = '验证码错误';
                return false;
            }
        }

        $map['username'] = $username;
        $userInfo = $this->where($map)->find();
        if (!$userInfo) {
            $this->error = '帐号不存在';
            return false;
        }
        if (user_md5($password) !== $userInfo['password']) {
            $this->error = '密码错误';
            return false;
        }
        // if ($userInfo['status'] === 0) {
        //     $this->error = '帐号已被禁用';
        //     return false;
        // }
        if ($userInfo['role'] != 0) {
            $res = Db::table('pudu_members')->where(['id' => $userInfo['userId'], 'status' => 1])->find();
            if (!$res) {
                $this->error = '帐号已被禁用';
                return false;
            }
        }

        // 获取菜单和权限
        $dataList = $this->getMenuAndRule($userInfo['id'], $userInfo['role']);
        if (!$dataList['menusList']) {
            $this->error = 'Permission denied!';
            return false;
        }

        if ($isRemember || $type) {
            $secret['username'] = $username;
            $secret['password'] = $password;
            $data['rememberKey'] = encrypt($secret);
        }

        // 保存缓存
        $key = $instance->getConf('jwt.key');
        $expire = $instance->getConf('jwt.expire');
        $refresh = $expire + 60; // 令牌失效60秒之内可以重新获取

        $data['userId'] = $userInfo['userId'];
        $data['role'] = $userInfo['role'];
        $data['adminId'] = $userInfo['id'];
        $data['expireDate'] = time() + $expire; // 规定令牌失效时间
        $data['refreshDate'] = time() + $refresh; // 规定令牌失效之后可重新获取的时间
        $data['authlist'] = $dataList['rulesList'];
        $authorization = JWT::encode($data, $key);

        // 返回信息
        $data['userInfo'] = $userInfo;
        $data['menusList'] = $dataList['menusList'];
        $data['authorization'] = $authorization;
        return $data;
    }

    /**
     * 获取菜单和权限
     * @param  array   $param  [description]
     */
    protected function getMenuAndRule($u_id, $role)
    {
        // TODO 获取四种角色对应的菜单信息
        $rules = null;
        $map = [];
        if ($u_id == 1) {
            $map['status'] = 1;
            $menusList = Db::table('admin_menu')->where($map)->order('sort asc')->select();
        } else {
            if ($role != 0) {
                $menusList = Db::table('admin_menu')->where($map)->order('sort asc')->select();
            } else {
                $groups = $this->get($u_id)->groups;
                $ruleIds = [];
                foreach ($groups as $k => $v) {
                    $ruleIds = array_unique(array_merge($ruleIds, explode(',', $v['rules'])));
                }
                $ruleMap['id'] = array('in', $ruleIds);
                $ruleMap['status'] = 1;
                // 重新设置ruleIds，除去部分已删除或禁用的权限。
                $rules = Db::table('admin_rule')->where(['status' => 1])->where('id', 'in', $ruleIds)->select();
                foreach ($rules as $k => $v) {
                    $ruleIds[] = $v['id'];
                    $rules[$k]['name'] = strtolower($v['name']);
                }

                empty($ruleIds) && $ruleIds = '';
                $menusList = Db::table('admin_menu')->where(['status' => 1])->where('rule_id', 'in', $ruleIds)->order('sort asc')->select();
            }
        }
        if (!$menusList) {
            return null;
        }

        //处理菜单成树状
        $tree = new Tree();
        $ret['menusList'] = $tree->list_to_tree($menusList, 'id', 'pid', 'child', 0, true, array('pid'));
        $ret['menusList'] = memuLevelClear($ret['menusList']);
        // 处理规则成树状

        if($role != 0){
            switch ($role) {
                case 1:
                    foreach ($ret['menusList'] as $k => $v) {
                        if ($v['title'] != '会员') {
                            unset($ret['menusList'][$k]);
                        }
                    }
                    break;
                case 2:
                    foreach ($ret['menusList'] as $k => $v) {
                        if ($v['title'] != '店铺') {
                            unset($ret['menusList'][$k]);
                        }
                    }
                    break;
                case 3:
                    foreach ($ret['menusList'] as $k => $v) {
                        if ($v['title'] != '市代') {
                            unset($ret['menusList'][$k]);
                        }
                    }
                    break;
                case 5:
                    foreach ($ret['menusList'] as $k => $v) {
                        if ($v['title'] != '区县') {
                            unset($ret['menusList'][$k]);
                        }
                    }
                    break;
            }
        }else{
            foreach ($ret['menusList'] as $k => $v) {
                if ($v['title'] == '会员' or $v['title'] == '店铺' or $v['title'] == '市代' or $v['title'] == '区县') {
                    unset($ret['menusList'][$k]);
                }
            }
        }

        if ($u_id == 1) {
            $map['status'] = 1;
            $menusList = Db::table('admin_menu')->where($map)->order('sort asc')->select();
            foreach ($ret['menusList'] as $k => $v) {
                if ($v['title'] != '系统' and $v['title'] != '参数' and $v['title'] != '账户') {
                    unset($ret['menusList'][$k]);
                }
            }
        }

        $ret['menusList'] = array_values($ret['menusList']);

        $ret['rulesList'] = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
        $ret['rulesList'] = rulesDeal($ret['rulesList']);
        return $ret;
    }

}
